// socket_handler
package handler

import (
	"fmt"
	proto "github.com/golang/protobuf/proto"
	"io"
	"net"
	p "tasty/protocol"
	"time"
)

var _chan_heart chan string
var _map_client map[net.Conn]string

func init() {
	_chan_heart = make(chan string, 100000000)
	_map_client = make(map[net.Conn]string, 10000)
}

func ClientHandler(conn net.Conn) {
	defer conn.Close()
	for {
		conn.SetReadDeadline(time.Now().Add(5 * time.Second))
		data := make([]byte, 4096)
		//Read the data waiting on the connection and put it in the data buffer
		n, err := conn.Read(data)
		if err == io.EOF {
			fmt.Printf("Client exit: %s\n", conn.RemoteAddr())
		}
		if err != nil {
			fmt.Printf("Read error: %s\n", err)
			return
		}

		conn.SetReadDeadline(time.Now().Add(10 * time.Second))

		protodata := new(p.Tasty)
		//Convert all the data retrieved into the ProtobufTest.TestMessage struct type
		err = proto.Unmarshal(data[0:n], protodata)
		if err != nil {
			cmd := protodata.GetCmd()
			// heart break
			if cmd == 0x1 {
				if session_id, ok := _map_client[conn]; ok {
					_chan_heart <- session_id
				}

			}

			if cmd == 0x10 {

			}
			fmt.Println(protodata.GetData())
		} else {
			fmt.Println(err.Error())
		}

		conn.SetReadDeadline(time.Now().Add(5 * time.Second))
	}

}

func heartbreak() {
	for session_id := range _chan_heart {
		fmt.Println("receive heart break from " + session_id)
	}
}
